// 用户模块
import { wechatLogin, logout, getUserInfo, updateUserInfo, getAddressList, addAddress as apiAddAddress, updateAddress as apiUpdateAddress, deleteAddress as apiDeleteAddress } from '@/api/user';

const state = {
  userInfo: uni.getStorageSync('userInfo') || null,
  token: uni.getStorageSync('token') || '',
  isLogin: !!uni.getStorageSync('token'),
  loginLoading: false,
  userInfoLoading: false
};

const getters = {
  // 获取用户信息
  getUserInfo: state => state.userInfo,
  // 判断用户是否登录
  isLoggedIn: state => state.isLogin,
  // 获取用户头像
  getUserAvatar: state => state.userInfo ? state.userInfo.avatar : '',
  // 获取用户名称
  getUserName: state => state.userInfo ? state.userInfo.name : '',
  // 获取用户学校
  getUserSchool: state => state.userInfo ? state.userInfo.school : '',
  // 获取用户专业
  getUserMajor: state => state.userInfo ? state.userInfo.major : '',
  // 获取用户年级
  getUserGrade: state => state.userInfo ? state.userInfo.grade : '',
  // 获取用户地址列表
  getUserAddresses: state => state.userInfo && state.userInfo.addresses ? state.userInfo.addresses : [],
  // 获取默认地址
  getDefaultAddress: state => {
    const addresses = state.userInfo && state.userInfo.addresses ? state.userInfo.addresses : [];
    return addresses.find(address => address.isDefault) || (addresses.length > 0 ? addresses[0] : null);
  },
  // 登录加载状态
  loginLoading: state => state.loginLoading,
  // 用户信息加载状态
  userInfoLoading: state => state.userInfoLoading
};

const mutations = {
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
    uni.setStorageSync('userInfo', userInfo);
  },
  
  // 设置token
  SET_TOKEN(state, token) {
    state.token = token;
    state.isLogin = !!token;
    uni.setStorageSync('token', token);
  },
  
  // 退出登录
  LOGOUT(state) {
    state.userInfo = null;
    state.token = '';
    state.isLogin = false;
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('token');
  },
  
  // 设置登录加载状态
  SET_LOGIN_LOADING(state, status) {
    state.loginLoading = status;
  },
  
  // 设置用户信息加载状态
  SET_USER_INFO_LOADING(state, status) {
    state.userInfoLoading = status;
  }
};

const actions = {
  /**
   * 微信登录
   * @param {Object} context - Vuex上下文
   * @param {Function} context.commit - 提交mutation的函数
   * @param {Object} [params] - 登录参数
   * @param {String} [params.code] - 微信登录获取的临时凭证
   * @param {Object} [params.userInfo] - 用户信息对象
   * @returns {Promise<Object>} 用户信息
   */
  async wechatLogin({ commit }, params = {}) {
    try {
      console.log('[用户模块] 开始微信登录', params);
      commit('SET_LOGIN_LOADING', true);
      
      // 调用API登录接口
      const res = await wechatLogin(params);
      
      // 处理响应
      if (res.code === 200) {
        console.log('[用户模块] 登录成功', res.data.userInfo);
        commit('SET_USER_INFO', res.data.userInfo);
        commit('SET_TOKEN', res.data.token);
        return Promise.resolve(res.data.userInfo);
      } else {
        console.warn('[用户模块] 登录失败', res.message);
        return Promise.reject(new Error(res.message || '登录失败'));
      }
    } catch (error) {
      console.error('[用户模块] 微信登录异常', error);
      return Promise.reject(error);
    } finally {
      commit('SET_LOGIN_LOADING', false);
    }
  },
  
  // 获取地址列表
  async fetchAddressList({ commit }) {
    try {
      const res = await getAddressList();
      if (res.code === 200) {
        // 需要更新整个用户信息数据
        const userInfoData = await getUserInfo();
        if (userInfoData.code === 200) {
          commit('SET_USER_INFO', userInfoData.data);
          return Promise.resolve(res.data);
        }
        return Promise.resolve(res.data);
      } else {
        return Promise.reject(res.message || '获取地址列表失败');
      }
    } catch (error) {
      console.error('获取地址列表失败', error);
      return Promise.reject(error);
    }
  },
  
  // 新增地址
  async addAddress({ commit }, address) {
    try {
      const res = await apiAddAddress(address);
      if (res.code === 200) {
        // 更新用户信息
        const userInfoData = await getUserInfo();
        if (userInfoData.code === 200) {
          commit('SET_USER_INFO', userInfoData.data);
        }
        return Promise.resolve(res.data);
      } else {
        return Promise.reject(res.message || '新增地址失败');
      }
    } catch (error) {
      console.error('新增地址失败', error);
      return Promise.reject(error);
    }
  },
  
  // 退出登录
  async logout({ commit }) {
    try {
      const res = await logout();
      if (res.code === 200) {
        commit('LOGOUT');
        return Promise.resolve();
      } else {
        return Promise.reject(res.message || '退出失败');
      }
    } catch (error) {
      return Promise.reject(error);
    }
  },
  
  // 获取用户信息
  async fetchUserInfo({ commit }) {
    try {
      commit('SET_USER_INFO_LOADING', true);
      const res = await getUserInfo();
      if (res.code === 200) {
        commit('SET_USER_INFO', res.data);
        return Promise.resolve(res.data);
      } else {
        return Promise.reject(res.message || '获取用户信息失败');
      }
    } catch (error) {
      return Promise.reject(error);
    } finally {
      commit('SET_USER_INFO_LOADING', false);
    }
  },
  
  // 更新用户信息
  async updateUserInfo({ commit }, userInfo) {
    try {
      const res = await updateUserInfo(userInfo);
      if (res.code === 200) {
        commit('SET_USER_INFO', res.data);
        return Promise.resolve(res.data);
      } else {
        return Promise.reject(res.message || '更新用户信息失败');
      }
    } catch (error) {
      return Promise.reject(error);
    }
  },
  
  // 更新地址
  async updateAddress({ commit }, { id, address }) {
    try {
      const res = await apiUpdateAddress(id, address);
      if (res.code === 200) {
        // 更新用户信息
        const userInfoData = await getUserInfo();
        if (userInfoData.code === 200) {
          commit('SET_USER_INFO', userInfoData.data);
        }
        return Promise.resolve(res.data);
      } else {
        return Promise.reject(res.message || '更新地址失败');
      }
    } catch (error) {
      console.error('更新地址失败', error);
      return Promise.reject(error);
    }
  },
  
  // 删除地址
  async deleteAddress({ commit }, addressId) {
    try {
      const res = await apiDeleteAddress(addressId);
      if (res.code === 200) {
        // 更新用户信息
        const userInfoData = await getUserInfo();
        if (userInfoData.code === 200) {
          commit('SET_USER_INFO', userInfoData.data);
        }
        return Promise.resolve(true);
      } else {
        return Promise.reject(res.message || '删除地址失败');
      }
    } catch (error) {
      console.error('删除地址失败', error);
      return Promise.reject(error);
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
